package com.dyp.globalexceptionhandler.ctr;

import com.dyp.globalexceptionhandler.model.CustomHttpStatusCodeException;
import com.dyp.globalexceptionhandler.model.ErrorResponse;
import org.apache.tomcat.util.ExceptionUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestControllerAdvice
//@ControllerAdvice //需要配合@ResponseBody使用
public class GlobalExceptionHandler {
    //全局异常处理，可以有多个ExceptionHandler
    /**
     * handle unexpect exception
     * @param ex
     * @param request
     * @param response
     * @return
     */
    @ExceptionHandler(CustomHttpStatusCodeException.class)
    @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR)
//    @ResponseBody
    public ErrorResponse handleAnyException(CustomHttpStatusCodeException ex, HttpServletRequest request,
                                            HttpServletResponse response) {
        ErrorResponse error = new ErrorResponse(request.getRequestURI(), request.getMethod(),
                HttpStatus.INTERNAL_SERVER_ERROR.value(), ex.getMessage() +"excepton class: " +ex.getClass()
                , null != ex.getCause() ? ex.getCause().getMessage():"");

        ex.printStackTrace();
        return error;
    }
}
